# dgr_queue_handler.py - Handle queue requests to run dgrs.
# Copyright 2009 Rob Myers <rob@robmyers.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import logging
import yaml
import traceback

import wsgiref.handlers
from google.appengine.runtime import DeadlineExceededError
from google.appengine.ext import webapp

from dgr import Dgr

class DgrWorker(webapp.RequestHandler):
    def post(self): # should run at most 1/s
        dgr_path = self.request.get('dgr-yaml-path')
        if (dgr_path):
            try:
                dgr = Dgr(dgr_path)
                dgr.run()
            except DeadlineExceededError, exc:
                # Re-throw the exception, returning an HTTP 500 result
                # This will result in this task being called again soon
                raise exc
            except Exception, e:
                logging.error(type(e))
                logging.error(e)
                logging.error(traceback.format_exc())
                # Re-throw the exception so we get called again soon
                raise e
    def load_yaml(self, yaml_file_path):
        yaml_file_text = file(yaml_file_path).read()
        yaml.safe_load(yaml_file_text)
    def load_dgr_config(self, dgr_path):
        self.load_yaml(dgr_path)
    def load_app_config(self):
        self.load_yaml("./config.yaml")

def main():
    wsgiref.handlers.CGIHandler().run(webapp.WSGIApplication([
                ('/run-dgr', DgrWorker)], debug=True))
    
if __name__ == '__main__':
    logging.getLogger().setLevel(logging.DEBUG)
    main()
